package com.taropan.wallpaper.util;


import java.io.BufferedReader;
import java.io.Closeable;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

/**
 * 
 * @author taro
 *
 */
public class HttpUtils {

	private static final String tag = HttpUtils.class.getSimpleName();
	
	/**
	 * POST请求
	 * @param mContext
	 * @param url
	 * @param paramsMap
	 * @return
	 */
	public static String doPost(Context mContext, String url, Map<String, String> paramsMap) {
		BaseHttpClient client = BaseHttpClient.newInstance(mContext, tag);
		HttpPost request = null;
		InputStream entityStream = null;
		String result = null;
		try {
			request = new HttpPost(url);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			for (Map.Entry<String, String> m : paramsMap.entrySet()) {
				params.add(new BasicNameValuePair(m.getKey(), m.getValue()));
			}
			request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			Log.d(tag, "request-url="+url + (params != null ? params.toString() : null));
//			LogUtils.fileLog(url, "参数：" + (params != null ? params.toString() : null));
			HttpResponse response = client.execute(request);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == 200) {
				entityStream = response.getEntity().getContent();
				result = convertStreamToString(entityStream);
			}
			Log.d(tag, "request-statusCode=" + statusCode);
		} catch (Exception e) {
			request.abort();
			e.printStackTrace();
			
		} finally {
			closeStream(entityStream);
			closeClient(client);
		}
		
		Log.d(tag, "result="+result);
//		LogUtils.fileLog(url, "返回结果：" + result);
		return result;
	}
	
	
	public static String doGet(String path) throws Exception {
		InputStream inStream = null;
		String result = null;
		HttpGet httpRequest = new HttpGet(path);
		HttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10 * 6000);
		HttpResponse httpResponse = httpClient.execute(httpRequest);
		
		System.out.println("doGet path:" + path);
		if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			inStream = httpResponse.getEntity().getContent();
			result = new String(Utils.readStream(inStream));
		} else {
			throw new Exception("conn exception");
		}
		
//		LogUtils.fileLog(path + "请求结果", result);
		
		return result;
	}
	
     /**
      * multipart/form-data	
      * @param actionUrl
      * @param params
      * @param files
      * @return
      * @throws Exception
      */
     public static String post(String actionUrl, Map<String, String> params,
            Map<String, File> files) throws Exception {
    	Log.d(tag, "request-url=" + actionUrl); 
        String result = null;
        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String PREFIX = "--", LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data";
        String CHARSET = "UTF-8";

        URL uri = new URL(actionUrl);
        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
        conn.setReadTimeout(60 * 1000); // 缓存的最长时间
        conn.setConnectTimeout(60 * 1000);
        conn.setDoInput(true);// 允许输入
        conn.setDoOutput(true);// 允许输出
        conn.setUseCaches(false); // 不允许使用缓存
        conn.setRequestMethod("POST");
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Charsert", "UTF-8");
        conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);

        // 首先组拼文本类型的参数
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINEND);
            sb.append("Content-Disposition: form-data; name=\""  + entry.getKey() + "\"" + LINEND);
            sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
            sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
            sb.append(LINEND);
            sb.append(entry.getValue());
            sb.append(LINEND);
        }
        Log.i("httptest","test"+sb.toString());
        DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
        outStream.write(sb.toString().getBytes());
        Log.i("httptest","testend");
        InputStream in = null; 
        // 发送文件数据
        if (files != null) {
            for (Map.Entry<String, File> file : files.entrySet()) {
                StringBuilder sb1 = new StringBuilder();
                sb1.append(PREFIX);
                sb1.append(BOUNDARY);
                sb1.append(LINEND);
                sb1.append("Content-Disposition: form-data; name=\"pic\"; filename=\"upload.jpg\"" + LINEND);
                sb1.append("Content-Type: image/jpeg; charset=" + CHARSET + LINEND);
                sb1.append(LINEND);
                outStream.write(sb1.toString().getBytes());

                InputStream is = new FileInputStream(file.getValue());
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = is.read(buffer)) != -1) {
                    outStream.write(buffer, 0, len);
                }

                is.close();
                outStream.write(LINEND.getBytes());
                Log.i("httptest:pic","test"+sb1.toString());
            }

            // 请求结束标志
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
            outStream.write(end_data);
            outStream.flush();
        }
        
     // 得到响应码
        int res = conn.getResponseCode();
        Log.i(tag, res + "-----------------1");
        if (res == 200) {
            in = conn.getInputStream();
            result = HttpUtils.convertStreamToString(in);
        }
        outStream.close();
        conn.disconnect();
        Log.d(tag, "result="+result);
        return result;
    }

	
	/**
	 * 请求图片
	 * 
	 * @param mContext
	 * @param url
	 * @return
	 */
	public static Bitmap getBitmapFromUrl(Context mContext, String url) {
		BaseHttpClient client = BaseHttpClient.newInstance(mContext, tag);
		HttpGet request = null;
		InputStream ins = null;
		try {
			request = new HttpGet(url);
			HttpResponse response = client.execute(request);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == 200) {
				ins = response.getEntity().getContent();
				BitmapFactory.Options opt = new BitmapFactory.Options();
				opt.inPreferredConfig = Bitmap.Config.RGB_565;
				opt.inPurgeable = true;
				opt.inInputShareable = true;
				return BitmapFactory.decodeStream(ins, null, opt);
			}
		} catch (Exception e) {
			request.abort();
			e.printStackTrace();
			return null;
		} finally {
			closeStream(ins);
			closeClient(client);
		}
		return null;
	}
        
	

	/**
	 * 请求地图图片
	 * 
	 * @param mContext
	 * @param url
	 * @return
	 */
	public static Bitmap getMapBitmapFromUrl(Context mContext, String url) {
		BaseHttpClient client = BaseHttpClient.newInstance(mContext, tag);
		HttpGet request = null;
		InputStream ins = null;
		try {
			request = new HttpGet(url);
			HttpResponse response = client.execute(request);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == 200) {
				ins = response.getEntity().getContent();
				BitmapFactory.Options opt = new BitmapFactory.Options();
				opt.inPreferredConfig = Bitmap.Config.ARGB_8888;
				opt.inPurgeable = true;
				opt.inInputShareable = true;
				return BitmapFactory.decodeStream(ins, null, opt);
			}
		} catch (Exception e) {
			request.abort();
			e.printStackTrace();
			return null;
		} finally {
			closeStream(ins);
			closeClient(client);
		}
		return null;
	}
	
	private static void closeClient(BaseHttpClient client) {
		if (client != null) {
			client.close();
			client = null;
		}
	}
	
	
   static String convertStreamToString(InputStream is) {
		StringBuilder sb = new StringBuilder();
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8 * 1024);
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException e) {
			sb.delete(0, sb.length());
		} finally {
			closeStream(is);
		}
		return sb.toString();
	}
	
	
	private static void closeStream(Closeable stream) {
		if (stream != null) {
			try {
				stream.close();
			} catch (IOException e) {
				
			}
		}
	}
}
